import Sig from './sig'
const HEADER = { 'Content-Type': 'application/json' }
const CREDS = 'include'
import config from './config'
function checkStatus (response) {
  if (response.status >= 200 && response.status < 300) { return response }
  const error = new Error(response.statusText)
  error.response = response
  throw error
}
const asyncFetch = async function (url, params, method = 'GET', conf = { headers: HEADER, credentials: CREDS, mode: 'cors', cache: 'default' }) {
  const { headers, credentials, mode, cache } = conf
  const sigObj = await Sig(params, config.salt)
  url = `${url}?sig=${sigObj.sig}&${sigObj.str}`
  let confFetch = { method, credentials }
  if (method === 'POST') {
    confFetch = { method, credentials, body: JSON.stringify({ ...params[1] }) }
  }
  return new Promise(function (resolve, reject) {
    fetch(url, confFetch)
      .then(checkStatus)
      .then(res => res.json())
      .then(res => { resolve(res) })
      .catch(err => { reject(err) })
  })
}

export default asyncFetch
